package caculate.stack;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;

/**
 * @program: rocsun
 * @description:
 * @author: yx.guo
 * @create: 2025-04-10 19:47
 **/
public class SimplifyPath {

    public static String simplifyPath(String path) {
        String[] pathArr = path.split("/");

        Deque<String> stack = new ArrayDeque<>();
        for (String p : pathArr) {
            switch (p) {
                case "..":
                    if (!stack.isEmpty()) stack.pop();
                    break;
                case ".":
                case "":
                    break;
                default:
                    stack.push(p);
            }
        }

        StringBuilder sb = new StringBuilder();
        if (stack.isEmpty()) {
            sb.append("/");
        } else {
            Iterator<String> iterator = stack.descendingIterator();
            while (iterator.hasNext()) {
                sb.append("/").append(iterator.next());
            }
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        String s = "/home/user/Documents/../Pictures";
        System.out.println(simplifyPath(s));
    }

}
